import React, { useState, useEffect, useRef, createRef } from 'react';
import { addXY, getAreaUser } from '../../apis/bigDate'
import content from '../../style/bigData/bigData.module.less'
import { Button, Drawer, Space, Input, message } from 'antd';
function CanvasBackgroundImage({ imageUrl }) {
  const canvasRef = useRef(null);
  const [mousePosition, setMousePosition] = useState({ x: 0, y: 0 });
  const [points, setPoints] = useState([])
  const keyWordsRef = createRef();
  const [size, setSize] = useState();
  const [open, setOpen] = useState(false);
  const [keyWords, setKeyWords] = useState('')
  const [messageApi, contextHolder] = message.useMessage();
  const [num, setNum] = useState(0)
  const key = 'updatable';
  useEffect(() => {
    const canvas = canvasRef.current;
    const ctx = canvas.getContext('2d');
    const backgroundImage = new Image();
    backgroundImage.src = imageUrl;
    backgroundImage.onload = function () {
      ctx.drawImage(backgroundImage, 0, 0, canvas.width, canvas.height);
    };
    // 获取区域坐标列表
    const getAreaXY = async () => {
      const { data } = await getAreaUser({ area_id: localStorage.getItem('areaId'), area_level: localStorage.getItem('areaLevel') })
      if (data.state === 1) {
        setPoints(...data.area_data)
        // 标记点位
        ctx.fillStyle = '#FAC858';
        data.area_data.forEach(point => {
          ctx.beginPath();
          ctx.arc(point.x, point.y, 6, 0, Math.PI * 2);
          ctx.fill();
        });
        if (data.area_data != []) {
          // 事件处理函数
          const handleMouseMove = (event) => {
            const rect = canvas.getBoundingClientRect();
            const x = event.offsetX;
            const y = event.offsetY;
            // 检查鼠标是否在点上
            data.area_data.forEach(point => {
              const isHover = Math.hypot(x - point.x, y - point.y) < 10;
              if (isHover) {
                // 鼠标移入点，执行操作，比如改变颜色
                ctx.beginPath();
                ctx.arc(point.x, point.y, 6, 0, 2 * Math.PI);
                ctx.fillStyle = 'red';
                ctx.fill();
                setNum(point.number)
              } else {
                // 鼠标移出点，恢复原来的颜色
                ctx.beginPath();
                ctx.arc(point.x, point.y, 6, 0, 2 * Math.PI);
                ctx.fillStyle = '#FAC858';
                ctx.fill();
              }
            });
          };
          // 添加鼠标移动事件监听
          canvas.addEventListener('mousemove', handleMouseMove);
          // 清理函数，移除事件监听
          return () => {
            canvas.removeEventListener('mousemove', handleMouseMove);
          };
        }


      }
    }
    getAreaXY()




  }, []);


  const handleMouseClick = (event) => {
    // 地图自动标点，每次标点打开该段代码即可
    const { offsetX, offsetY } = event.nativeEvent;
    setMousePosition({ x: offsetX, y: offsetY });
    openTrue()



  };
  const openTrue = () => {
    setSize('large');
    setOpen(true);

  };
  const onClose = () => {
    setOpen(false);
  };
  // 确定
  const onOk = () => {
    setOpen(false);
    addXYAsync()
  };
  // 农药销售数据
  const addXYAsync = async () => {
    messageApi.open({
      key,
      type: 'loading',
      content: '新增中...',
    });
    const { data } = await addXY({ ...mousePosition, area_name: keyWords, area_pid: localStorage.getItem('areaId') })

    if (data.state === 1) {

      messageApi.open({
        key,
        type: 'success',
        content: '新增成功!',
        duration: 2,
      });


    } else {
      messageApi.open({
        key,
        type: 'error',
        content: data.msg,
        duration: 2,
      });
    }
  };

  return (
    <>
      {contextHolder}
      <canvas ref={canvasRef} width={650} height={650} onClick={(e) => handleMouseClick(e)} />
      <Drawer
        title={'地区标点确认框'}
        placement="right"
        size={size}
        onClose={onClose}
        open={open}
        extra={
          <Space>
            <Button onClick={onClose}>取消</Button>
            <Button type="primary" onClick={onOk}>
              确定
            </Button>
          </Space>
        }
      >
        <Input placeholder="地区名" type="text" ref={keyWordsRef} value={keyWords} onChange={() => {
          setKeyWords(keyWordsRef.current.input.value)
        }} />
      </Drawer>
      <span className={content.center_hu}>
        共有{num}户
      </span>
    </>
  )
}

export default CanvasBackgroundImage;
